<?php

namespace app\admin\service\iot\statistics;

use app\common\Message;
use app\model\iot_model\IotDevice;
use app\model\iot_model\IotDeviceCategory;
use app\model\iot_model\IotRoom;
use app\model\sync_model\SyncReport;
use app\model\sync_model\SyncUser;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;

class Statistics
{
    use  Message;

    public function numberOfDevices($data): bool
    {
        $iotDevice = new IotDevice();
        $where['unit_id'] = $data['platform_unit_id'];
        $list = $iotDevice->where($where)->field('id,is_online,is_hardware')->select();
        $info['device_num'] = count($list);//总设备数
        $info['online'] = 0; //在线设备数量
        $info['hardware'] = 0; //非电设备数量
        foreach ($list as $item){
            if($item['is_online'] == 1){
                $info['online']+= 1;
            }
            if($item['is_hardware'] == 1){
                $info['hardware'] += 1;
            }
        }
        $info['offline'] = $info['device_num']-$info['online']; //离线设备数量
        $info['device_num_proportion'] = $info['device_num'] == 0?0:100; //总设备占比
        $info['online_proportion'] = $info['online'] == 0?0:intval(removeTrailingZero(number_format(($info['online']/$info['device_num'])*100,1)));//在线设备占比
        $info['hardware_proportion'] = $info['hardware'] == 0?0:intval(removeTrailingZero(number_format(($info['hardware']/$info['device_num'])*100,1)));//非电设备占比
        $info['offline_proportion'] = $info['offline'] == 0?0:intval(removeTrailingZero(number_format(($info['offline']/$info['device_num'])*100,1)));//离线设备占比
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function iotOverview($data): bool
    {
        $iotDevice = new IotDevice();
        $where['unit_id'] = $data['platform_unit_id'];
        $where['is_hardware'] = 0;
        $hardware = $iotDevice->where($where)->withCount(['userNum'])->field('id,is_online,is_hardware')->select();//硬件总数【有电设备：包含在线、离线】
        $info['hardware'] = count($hardware);
        $info['userNum'] = 0;
        if(count($hardware)>0){
            foreach($hardware as $item){
                $info['userNum'] += $item['user_num_count'];
            }
        }
        $iotRoom = new IotRoom();
        $info['room'] = $iotRoom->where('company_id',$data['platform_unit_id'])->count();
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function moduleMonitoring($data): bool
    {
        $iotDevice = new IotDevice();
        $where['unit_id'] = $data['platform_unit_id'];
        $where['is_hardware'] = 0;
        $hardware = $iotDevice->where($where)->withCount(['userNum'])->field('id,is_online,is_hardware')->select();//硬件总数【有电设备：包含在线、离线】
        $info['hardware'] = count($hardware);
        //左边模块数量【同样的设备算一个模块数】
        $device_ids = $iotDevice->where($where)->with(['getModuleNum'])->field('id,name')->select();
//        var_dump($device_ids->toArray());die;
        /*查询相同的设备内模块最多的*/
        $moduleCount = 0; //所有模块的总数
        $titleCount = []; //每个软件的模块总数
        $result = [];
        foreach ($device_ids as $item) {
            $name = $item['name'];
            $moduleNumCount = count($item['getModuleNum']);
            //计算所有模块的总数
            $moduleCount += $moduleNumCount;
            // 如果这个 name 还不存在于结果数组中
            if (!isset($result[$name]) || count($result[$name]['getModuleNum']) < $moduleNumCount) {
                $result[$name] = $item->toArray(); // 更新为当前项
            }
            //计算每个软件里每个模块的总点击数
            foreach ($item['getModuleNum'] as $module) {
                $title = $module['title'];
                // 初始化相应 name 的 title 计数
                if (!isset($titleCount[$name][$title])) {
                    $titleCount[$name][$title] = 0;
                }
                // 累加该 title 的数量
                $titleCount[$name][$title]++;
            }

        }
        $totalCount = 0;
        foreach ($result as $item) {
            $totalCount += count($item['getModuleNum']);
        }
        $info['moduleNum'] = $totalCount;
        //计算每个模块的点击数量，占比【按时间分页。每页5个。】
        $moduleList = [];
        if(count($titleCount)>0){
            //所有设备名称
            $device_name = new IotDeviceCategory();
            $list = $device_name->select();
            $temp_name = [];
            foreach($list as $value){
                $temp_name[$value['id']] = $value;
            }
            foreach($titleCount as $key=>$item){
                $infos = [];
                foreach ($item as $k=>$v){
                    $temp_info['module_name'] = $k;
                    $temp_info['module_num'] = $v;
                    $temp_info['module_proportion'] = removeTrailingZero(number_format(($v/$moduleCount)*100,1));
                    $temp_info['device_name'] = $temp_name[$key]['name'];
                    $infos [] = $temp_info;
                }
                $moduleList[] = $infos;
            }
        }
        if(!empty($moduleList)){
            $moduleList = arrtre($moduleList);
            $info['list'] = paginateArray($moduleList,$data['page'],$data['pageSize']);
        }else{
            $info['list'] = [];
        }
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    public function userDeviceStatistic($data)
    {
        $iotDevice = new IotDevice();
        $where['unit_id'] = $data['platform_unit_id'];
        $where['is_hardware'] = 0;
        $hardware = $iotDevice->where($where)->withCount(['userNum'])->field('id,is_online,is_hardware')->select();
        $info['device_count'] = count($hardware);//硬件总数【有电设备：包含在线、离线】
        //所有设备名称
        $device_name = new IotDeviceCategory();
        $list = $device_name->select();
        $temp_name = [];
        foreach($list as $value){
            $temp_name[$value['id']] = $value;
        }
        $nameCounts  = [];
        foreach ($hardware as $item) {
            $name = $item['name'];
            $id = $item['id'];

            if (!isset($nameCounts[$name])) {
                $nameCounts[$name] = [
                    'count' => 0,
                    'ids' => []
                ];
            }
            $nameCounts[$name]['count']++;
            $nameCounts[$name]['ids'][] = $id; // 保存对应的 id
        }
        // 构造输出结果数组
        $result = [];
        foreach ($nameCounts as $name => $infos) {
            //获取用户数量、男女
            $userNumber = 0;
            $userManNumber = 0;
            $userWomanNumber = 0;
            $userCount = SyncUser::query()->where('device_id','in',$infos['ids'])->field('id,sex')->select();
            if(count($userCount)>0){
                $userNumber = count($userCount);
                foreach($userCount as $item){
                    if($item['sex'] == 1){
                        $userManNumber += 1;
                    }else{
                        $userWomanNumber += 1;
                    }
                }
            }
            $result[] = [
                'name' => $name,
                'device_name'=>$temp_name[$name]['name'],
                'count' => $infos['count'],
                'proportion'=> removeTrailingZero(number_format(($infos['count']/$info['device_count'])*100,1)),
                'userCount'=>$userNumber,
                'userManNumber'=>$userManNumber,
                'userWomanNumber'=>$userWomanNumber,
            ];
        }
        $ret = paginateArray($result,$data['page'],$data['pageSize']);
        $ret['hardware'] = $info['device_count'];
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function Ranking($data): bool
    {
        //获取个体咨询室名称
        $iotRoom = new IotRoom();
        $info = $iotRoom->where('unit_id',$data['platform_unit_id'])
            ->with(['functionRoomName','getDeviceList'=>function(Query $query){
                $query->withCount(['useCount']);
            },'functionRoomForName'])
            ->field('id,name_id,type_id')
            ->select();
        //处理数据
        if(count($info)>0){
            $info = $info->toArray();
            foreach($info as &$item){
                //求所有登录次数的和
                $item['count'] = array_reduce($item['getDeviceList'], function($carry, $item) {
                    return $carry + $item['use_count_count'];
                }, 0);
                //获取封面图
                $item['img'] = $item['functionRoomForName']['img'];
            }
            // 使用usort根据count进行倒序排序
            usort($info, function($a, $b) {
                return $b['count'] <=> $a['count']; // 倒序排列
            });
            //给所有排序赋值排名
            foreach($info as $key=>&$value){
                $value['ranking'] = $key+1;
                unset($value['getDeviceList']);
                unset($value['functionRoomForName']);
                unset($value['name_id']);
                unset($value['type_id']);
            }
            $ret = paginateArray($info,$data['page'],$data['pageSize']);
        }else{
            $ret = [];
        }
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }
}